<template>
	<view class="content">
		<button @click="getMessage()">订阅</button>
		<button @click="send()">发送订阅消息</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tip: 0,
			}
		},
		methods: {
			// 点击订阅信息
			getMessage() {
				if(this.tip == 0) {
					this.tip++
				}else{
					return uni.showToast({
						title: '点击发送订阅消息',
						icon: 'none'
					})
				}
				uni.requestSubscribeMessage({
					tmplIds: ['MHpo_5380HaMDGYPM45YZFMbyMcf9blVm93BFKdwTok'],
					success(result) {
						console.log(uni.getStorageSync('token'), "活动订阅信息");
						if (result["MHpo_5380HaMDGYPM45YZFMbyMcf9blVm93BFKdwTok"] === 'accept') {
							// 订阅之后，就得将此用户信息记录下来，方便后续发送订阅消息
							uniCloud.callFunction({
								name: 'subscribe',
								data: {
									user_id: uni.getStorageSync('token')._id,
									openid: uni.getStorageSync('token').openid,
									state: 1, // 正常
									type: 1 // 签到
								},
								success: (res) => {
									console.log(res, "订阅成功返回的数据信息");
									uni.showToast({
										title: '订阅成功',
										icon: 'success'
									})
								},
								fail: () => {
									uni.showToast({
										title: '订阅失败',
										icon: 'error',
										duration: 2000
									})
								}
							})
						}
					}
				})
			},
			// 发送订阅消息
			send() {
				if(this.tip == 0) {
					return uni.showToast({
						title: '有病吧，先订阅',
						icon: 'none'
					})
				}else{
					this.tip = 0
				}
				let params = {
					thing1: {
						value: "新的活动"
					},
					thing2: {
						value: "电车价格历史最低"
					},
					thing3: {
						value: "快去看看吧~"
					},
					time4: {
						value: "2019年10月1日 15:01:01"
					}
				}
				// 订阅之后，就得将此用户信息记录下来，方便后续发送订阅消息
				uniCloud.callFunction({
					name: 'sendMessage',
					data: {
						touser: uni.getStorageSync('token').openid, // 用户的openid
						template_id: 'MHpo_5380HaMDGYPM45YZFMbyMcf9blVm93BFKdwTok', //模板id
						data: params
					},
					success: (res) => {
						console.log(res, "发送订阅消息成功--");
						uni.showToast({
							title: '订阅成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						console.log(err, "发送订阅消息失败")
						uni.showToast({
							title: '订阅失败',
							icon: 'error',
							duration: 2000
						})
					}
				})
			},
		}
	}
</script>

<style>
	.content{
		padding: 20rpx;
	}
	button{
		margin: 20rpx 0;
	}
</style>